package com.huiyeji.mail.trigger;

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class CacheCleaner {

    private final Runnable runnable;

    public CacheCleaner(Runnable runnable) {
        this.runnable = runnable;
        this.start();
    }

    public void start(){
        // 创建Timer实例
        Timer timer = new Timer();

        // 创建定时任务
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                runnable.run();
            }
        };

        // 计算第一次执行时间（第二天凌晨3点）
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 3);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        // 如果当前时间已经过了凌晨3点，则设置为明天凌晨3点
        if (calendar.getTime().before(new Date())) {
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }

        Date firstTime = calendar.getTime();

        // 安排任务每天执行一次（24小时间隔）
        timer.scheduleAtFixedRate(task, firstTime, 24 * 60 * 60 * 1000);
//        timer.scheduleAtFixedRate(task, new Date(), 1000);
    }
}
